<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\model;
use think\facade\Db;
use think\facade\Session;
use think\facade\Cache;

/**
* 企业微信接口
**/
class QyWechatApi 
{
	/**
	* 获取通讯录access_token
	**/
	static	public	function getStaffAccessToken($wid=''){
		$wid = $wid ?: Session::get('wid');
		$config = Db::table('kt_wework_config')->where('wid',$wid)->find();
		$cacheName = $config?$config['corp_id'].'-staff_access_token':'-staff_access_token';
		$user_secret = $config?$config['user_secret']:"";
		$corp_id = $config?$config['corp_id']:"";
		if(!Cache::get($cacheName)){
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$corp_id.'&corpsecret='.$user_secret;
			$res = json_decode(curlGet($url),1);
			if($res['errcode'] !== 0){
				return '';
			}
			Cache::set($cacheName,$res['access_token'],6900);
		}

		return Cache::get($cacheName);
	}
	/**
	* 获取客户联系人access_token
	**/
	static	public	function getCustomerAccessToken($wid=''){
		$wid = $wid ?: Session::get('wid');
		$config = Db::table('kt_wework_config')->where('wid',$wid)->find();
		$cacheName = $config?$config['corp_id'].'-customer_access_token':'-customer_access_token';
		$customer_secret = $config?$config['customer_secret']:"";
		$corp_id = $config?$config['corp_id']:"";
		if(!Cache::get($cacheName)){
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$corp_id.'&corpsecret='.$customer_secret;
			$res = json_decode(curlGet($url),1);
			if($res['errcode'] !== 0){
				return '';
			}
			Cache::set($cacheName,$res['access_token'],6900);
		}

		return Cache::get($cacheName);
	}
	/**
	* 获取自建应用 access_token
	**/
	static	public	function getSelfappAccessToken($wid=''){
		$wid = $wid ?: Session::get('wid');
		$config = Db::table('kt_wework_config')->where('wid',$wid)->find();
		$selfapp = Db::table('kt_wework_selfapp')->where('wid',$wid)->find();
		$cacheName = $config?$config['corp_id'].'-selfapp_access_token':'-selfapp_access_token';
		$secret = $selfapp?$selfapp['secret']:"";
		$corp_id = $config?$config['corp_id']:"";
		if(!Cache::get($cacheName)){
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$corp_id.'&corpsecret='.$secret;
			$res = json_decode(curlGet($url),1);
			if($res['errcode'] !== 0){
				return '';
			}
			Cache::set($cacheName,$res['access_token'],6900);
		}

		return Cache::get($cacheName);
	}
	/**
	* 获取客户联系人详情
	**/
	static	public	function getExternalDetail($wid,$externalUserId){
		$wid = $wid?$wid:Session::get('wid');
		$accessToken = self::getCustomerAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token='.$accessToken.'&external_userid='.$externalUserId;
		$res = json_decode(curlGet($url),1);
		return $res;
	}

	/*
 	 * 获取配置了客户联系功能的成员列表 
 	*/
    public static function get_follow_user_list($wid){
	    $wid = $wid ?: Session::get('wid');
        $token = self::getCustomerAccessToken($wid);
		$res = json_decode(curlGet("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_follow_user_list?access_token=".$token,array()),1);
		
		return $res["follow_user"];
    }

	/**
	* 获取客户联系人列表
	**/
	static	public	function getCustomerList($wid=NULL,$userid){
		$accessToken = self::getCustomerAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token='.$accessToken;
		$data = [
			"userid_list" => $userid,
			"cursor" => '',
			"limit" => 100
		];
		$res = [];
		while (1) {
			$result = json_decode(curlPost($url,json_encode($data)),1);
			if ($result['errcode'] !== 0) {
				break;	
			}
			$res = array_merge($res , $result['external_contact_list']);
			if(isset($result['next_cursor']) && $result['next_cursor'] != ''){
				$data['cursor'] = $result['next_cursor'];
			}else{
				break;
			}
		}
		return $res;
	}
	/**
	* 获取配置了客户联系功能的成员列表
	**/
	static	public	function getFollowUserList($wid){
		$accessToken = self::getCustomerAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_follow_user_list?access_token='.$accessToken;
		$res = json_decode(curlGet($url),1);
		return $res;
	}

	/**
	* 获取企业员工列表
	**/
	static	public	function getStaffList($departmentId,$wid=''){
		$wid = $wid ?: Session::get('wid');
		$accessToken = self::getSelfappAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token='.$accessToken.'&department_id='.$departmentId;
		$res = json_decode(curlGet($url),1);
		return $res;
	}
	/**
	* 获取企业部门列表
	* @param $userId int   企业账户主键id
	**/
	static	public	function getDepartmentList($wid=''){
		$wid = $wid ?: Session::get('wid');
		$accessToken = self::getSelfappAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token='.$accessToken;
		$res = json_decode(curlGet($url),1);
		return $res;
	}

	/**
	* 获取群列表
	**/
	static	public	function getExternalGroupchatList($wid=''){
		$wid = $wid ?: Session::get('wid');
		$accessToken = self::getCustomerAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token='.$accessToken;
		$data = json_encode([
			'status_filter'=> 0,
			'cursor' => '',
			'limit' => 100
		]);
		$res = [];
		while (1) {
			$result = json_decode(curlPost($url,$data),1);
			if ($result['errcode'] !== 0) {
				break;	
			}
			$res = array_merge($res , $result['group_chat_list']);
			if(isset($result['next_cursor']) && $result['next_cursor'] != ''){
				$data['cursor'] = $result['next_cursor'];
			}else{
				break;
			}
		}
		return $res;
	}
	/**
	* 获取群详情
	**/
	static	public	function getExternalGroupchatDetail($chatId,$wid=''){
		$wid = $wid ?: Session::get('wid');
		$accessToken = self::getCustomerAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token='.$accessToken;
		$data = json_encode([
			'chat_id' => $chatId,
			'need_name' => 1
		]);
		$res = json_decode(curlPost($url,$data),1);
		return $res;
	}
	/**
	* 获取企业标签
	**/
	static	public	function getCorpTagList($wid='',$params = []){
		$wid = $wid ?: Session::get('wid');
		$accessToken = self::getCustomerAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list?access_token='.$accessToken;
		$data = json_encode($params);
		$res = json_decode(curlPost($url,$data),1);
		return $res;
	}
	/**
	* 添加企业标签
	* group_id 标签组id
	* group_name 标签组名称
	* tag 标签详情数组，只有name即可
	**/
	static	public	function addCorpTag($param,$wid=''){
		$wid = $wid ?: Session::get('wid');
		$accessToken = self::getCustomerAccessToken($wid);
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_corp_tag?access_token=" . $accessToken,
			json_encode($param)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	/**
	* 编辑企业标签
	* param["id"] 标签或标签组的id
	* param["name"] 新的标签或标签组名称
	**/
	static	public	function editCorpTag($param = [],$wid = NULL){
		$accessToken = self::getCustomerAccessToken($wid);
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/edit_corp_tag?access_token=" . $accessToken,
			json_encode([
				"id" => $param['id'],
				"name" => $param['name']
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	/**
	* 删除企业标签
	* param["tag_id"] 标签的id列表
	* param["group_id"] 标签组的id列表
	**/
	static	public	function delCorpTag($param,$wid=''){
		$wid = $wid ?: Session::get('wid');
		$accessToken = self::getCustomerAccessToken($wid);
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_corp_tag?access_token=" . $accessToken,
			json_encode($param)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	/**
	* 编辑客户企业标签    //企业可通过此接口为指定成员的客户添加上由企业统一配置的标签。
	* userid 添加外部联系人的userid
	* external_userid 外部联系人userid
	* add_tag 要标记的标签列表
	* remove_tag 要移除的标签列表
	**/
	static	public	function editMarkTag($param,$wid=''){
		$wid = $wid ?: Session::get('wid');
		$accessToken = self::getCustomerAccessToken($wid);
		$data = [
			"userid" => $param['userid'],
			"external_userid" => $param['external_userid'],
			"add_tag" => $param['add_tag'],
			"remove_tag" => $param['remove_tag']
		];
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag?access_token='.$accessToken;
		$res = json_decode(curlPost($url,json_encode($data,320)),1);
		return $res;
	}
	/**
	* 修改客户备注信息    
	* @param userid 添加外部联系人的userid
	* @param external_userid 外部联系人userid
	* @param remark 此用户对外部联系人的备注，最多20个字符
	* @param description 此用户对外部联系人的描述，最多150个字符
	**/
	static public function externalcontactRemark($param,$wid=''){
		$token = self::getCustomerAccessToken($wid);
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/remark?access_token=" . $token,
			json_encode($param)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	/**
	* 配置客户联系「联系我」方式。
	* type 联系方式类型,1-单人, 2-多人
	* scene 场景，1-在小程序中联系，2-通过二维码联系
	* remark 联系方式的备注信息，用于助记，不超过30个字符
	* skip_verify 外部客户添加时是否无需验证，默认为true
	* state 企业自定义的state参数
	* user 使用该联系方式的用户列表
	**/
	static	public	function addContactWay($params,$wid=''){
		$wid = $wid ?: Session::get('wid');
		$accessToken = self::getCustomerAccessToken($wid);

		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_contact_way?access_token=" . $accessToken,
			json_encode([
				"type" => $params['type'],
				"scene" => $params['scene'],
				"user" => $params['user'],
				"state" => $params['state'],
				// "remark" => $params['remark'],
				"skip_verify" => $params['skip_verify']
			],320)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	/**
	* 更新客户联系「联系我」方式。
	* config_id 联系方式的配置id
	* user 使用该联系方式的用户列表，将覆盖原有用户列表
	* remark 	联系方式的备注信息，不超过30个字符，将覆盖之前的备注
	**/
	static	public	function updateContactWay($params,$wid=''){
		$wid = $wid ?: Session::get('wid');
		$accessToken = self::getCustomerAccessToken($wid);
		$data["config_id"] = $params["config_id"];
		if(isset($params["user"]))$data["user"] = $params["user"];
		if(isset($params["skip_verify"]))$data["skip_verify"] = $params["skip_verify"];
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/update_contact_way?access_token=" . $accessToken,
			json_encode($data,320)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	/**
	* 获取企业已配置的「联系我」方式
	* config_id 联系方式的配置id
	**/
	static	public	function getContactWay($configId,$wid=''){
		$wid = $wid ?: Session::get('wid');
		$accessToken = self::getCustomerAccessToken($wid);
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_contact_way?access_token=" . $accessToken,
			json_encode([
				"config_id" => $configId
			],320)
		);
		$resp_arr = json_decode($body, 1);
	}
	/**
	* 删除企业已配置的「联系我」方式
	* config_id 联系方式的配置id
	**/
	static	public	function delContactWay($configId,$wid=''){
		$wid = $wid ?: Session::get('wid');
		$accessToken = self::getCustomerAccessToken($wid);
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_contact_way?access_token=" . $accessToken,
			json_encode([
				"config_id" => $configId
			],320)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	/**
	* 发送新客户欢迎语
	* welcome_code 通过添加外部联系人事件推送给企业的发送欢迎语的凭证
	* attachments 发送内容附件
	**/
	static	public	function sendWelcomeMsg($wid,$param){
		$accessToken = self::getCustomerAccessToken($wid);
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/send_welcome_msg?access_token=" . $accessToken,
			json_encode($param,320)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	/**
	* 创建企业群发
	* external_userid 客户的外部联系人id列表
	* sender 发送企业群发消息的成员userid
	* text 文字数组
	* attachments 附件，最多支持添加9个附件
	**/
	static	public	function addMsgTemplate($wid,$external_userid=NULL,$sender=NULL,$text,$attachments){
		$accessToken = self::getCustomerAccessToken($wid);
		if($external_userid) $data["external_userid"] = $external_userid;
		if($sender) $data["sender"] = $sender;
		if($text) $data["text"] = $text;
		if($attachments) $data["attachments"] = $attachments;
		if(!$sender && !$external_userid) return "必填参数不可缺少";
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_msg_template?access_token=" . $accessToken,
			json_encode($data,320)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	/**
	* 创建客户群群发
	* external_userid 客户的外部联系人id列表
	* sender 发送企业群发消息的成员userid
	* text 文字数组
	* attachments 附件，最多支持添加9个附件
	**/
	static	public	function addMsgGroup($wid,$sender,$text,$attachments,$group=NULL){
		$accessToken = self::getCustomerAccessToken($wid);
		if($group)$data["chat_type"] = $group;
		$data["sender"] = $sender;
		if($text) $data["text"] = ["content"=>$text];
		if($attachments) $data["attachments"] = $attachments;
		if(!$sender) return "必填参数不可缺少";
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_msg_template?access_token=" . $accessToken,
			json_encode($data,320)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	/**
	* 获取群发成员发送任务列表
	* msgid 群发消息的id
	**/
	static	public	function getGroupmsgTask($wid,$msgid=NULL){
		$accessToken = self::getCustomerAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_groupmsg_task?access_token='.$accessToken;
		$res = [
			'errcode' => 0,
			'errmsg' => 'ok',
			'task_list' => [],
		];
		while (1) {
			$data = [];
			if($msgid) $data["msgid"] = $msgid;
			$info = json_decode(curlPost($url,json_encode($data)),1);
			if($info['errcode'] != 0){
				$res =  $info;
				break;
			}
			$res['task_list'] = array_merge($res['task_list'],$info['task_list']);
			if($info['next_cursor'] == ''){
				break;
			}
			$data['cursor'] = $info['next_cursor'];
		}
		return $res;
	}
	/**
	* 获取企业群发成员执行结果
	* msgid 群发消息的id
	* userid 发送成员userid
	**/
	static	public	function getGroupmsgSendResult($wid,$userid,$msgid){
		$accessToken = self::getCustomerAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_groupmsg_send_result?access_token='.$accessToken;
		$res = [
			'errcode' => 0,
			'errmsg' => 'ok',
			'send_list' => [],
		];
		while (1) {
			$data["userid"] = $userid;
			$data["msgid"] = $msgid;
			$info = json_decode(curlPost($url,json_encode($data)),1);
			if($info['errcode'] != 0){
				$res =  $info;
				break;
			}
			$res['send_list'] = array_merge($res['send_list'],$info['send_list']);
			if($info['next_cursor'] == ''){
				break;
			}
			$data['cursor'] = $info['next_cursor'];

			
		}
		return $res;
	}

	/**
	* 获取「联系客户统计」数据
	* @param $userid 成员userid
	* @param $partyid 部门id    部门id与成员uesrid不能同时为空
	**/
	static public function getUserBehaviorData($staffs=[],$partyid=[],$start_time,$end_time){
		$wid = Session::get('wid');
		$accessToken = self::getCustomerAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_user_behavior_data?access_token='.$accessToken;
		$data = json_encode([
			'userid'=>$staffs,
			'partyid'=>$partyid,
			'start_time'=>$start_time,
			'end_time'=>$end_time,
		]);
		$res = json_decode(curlPost($url,$data),1);
		return $res;
	}
	/**
	* 上传临时素材
	* $type 媒体文件类型，分别有图片（image）、语音（voice）、视频（video），普通文件（file）
	**/
	static	public	function mediaUpload($wid,$path,$type){
		$accessToken = self::getSelfappAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token='.$accessToken.'&type='.$type;
		if(class_exists('CURLFile')){
		    $data = ['media' => new \CURLFile($path)];
		}else{
		    $data = ['media' => $path];
		}
		$res = json_decode(curlPost($url,$data),1);
		return $res;
	}

	/**
	* 上传临时素材
	* $type 媒体文件类型，分别有图片（image）、语音（voice）、视频（video），普通文件（file）
	**/
	static	public	function uploadAttachment($wid,$path,$type){
		$accessToken = self::getSelfappAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload_attachment?access_token='.$accessToken.'&media_type='.$type."&attachment_type=1";
		if(class_exists('CURLFile')){
		    $data = ['media' => new \CURLFile($path)];
		}else{
		    $data = ['media' => $path];
		}
		$res = json_decode(curlPost($url,$data),1);
		return $res;
	}
	
	static public function curl_posts($url, $data = null){
     	//创建一个新cURL资源
     	$curl = curl_init();
     	//设置URL和相应的选项 
     	curl_setopt($curl, CURLOPT_URL, $url);
     	if (!empty($data)){
      		curl_setopt($curl, CURLOPT_POST, 1);
      		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
     	}
     	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     	//执行curl，抓取URL并把它传递给浏览器
     	$output = curl_exec($curl);
     	//关闭cURL资源，并且释放系统资源
     	curl_close($curl);
     	return $output;
    }

	/**
	* 获取指定自建应用配置信息
	* agentid 自建应用id
	**/
	static	public	function getAgent($wid,$agentid){
		$accessToken = self::getSelfappAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/agent/get?access_token='.$accessToken.'&agentid='.$agentid;
		$res = json_decode(curlGet($url),1);
		return $res;
	}

	/**
	* 添加入群欢迎语素材 
	**/
	static public function groupWelcomeTemplate($wid,$text,$welcomeData=NULL,$send_status){
		$accessToken = self::getCustomerAccessToken($wid);
		if(!$text) return "缺少参数";
		$text = str_replace('[插入客户昵称]', "%NICKNAME%", $text);
		if($welcomeData)$data = $welcomeData;
		$data["text"] = ["content"=>$text];
		if($send_status)$data["notify"] = $send_status;
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/add?access_token=".$accessToken,
			json_encode($data)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	/**
	* 修改入群欢迎语素材 
	**/
	static public function editWelcomeTemplate($wid,$template_id,$text,$welcomeData=NULL){
		$accessToken = self::getCustomerAccessToken($wid);
		if(!$text) return "缺少参数";
		if($welcomeData)$data = $welcomeData;
		$data["text"] = ["content"=>$text];
		$data["template_id"] = $template_id;
		$text = str_replace('[插入客户昵称]', "%NICKNAME%", $text);
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/edit?access_token=".$accessToken,
			json_encode($data)
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	/**
	* 删除入群欢迎语素材 
	**/
	static public function delWelcomeTemplate($wid,$template_id){
		$accessToken = self::getCustomerAccessToken($wid);
		if(!$template_id) return "缺少参数";
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/del?access_token=".$accessToken,
			json_encode([
				"template_id" => $template_id
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	/**
	* 给成员推送消息 
	* 文本消息
	**/
	static	public	function sendText($wid,$userid,$content){
		$accessToken = self::getSelfappAccessToken($wid);
		$selfapp = Db::table('kt_wework_selfapp')->where('wid',$wid)->find();
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$accessToken,
			json_encode([	
				"touser" => $userid,
				"msgtype" => 'text',
				"agentid" => $selfapp["agent_id"],
				"text"=>[
					"content" => $content
				]
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}
	
	/**
	* 给成员链接
	**/
	static public function send_textcard($userid,$wid='',$title,$description,$url){
		$wid = $wid?$wid:Session::get('wid');
		$selfapp = Db::table('kt_wework_selfapp')->where('wid',$wid)->find();
		$accessToken = self::getSelfappAccessToken($wid);
		$body = curlPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$accessToken,
			json_encode([
				"touser" => $userid,
				"msgtype" => 'textcard',
				"agentid" => $selfapp["agent_id"],
				"textcard"=>[
					"title" => $title,
					"description" => $description,
					"url" => $url,
				]
			])
		);
		$resp_arr = json_decode($body, 1);
		return $resp_arr;
	}

	/*
	* 获取客户授权信息
	*/
	static public function getuserinfo($wid,$code){
		$token = self::getSelfappAccessToken($wid);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$token.'&code='.$code;
		$resArr = json_decode(curlGet($url),1);
		return $resArr;
	}


	static public function robotImages($image){
		$robot = Db::table('kt_base_robot')->select()->toArray();
		if(!$robot[0]) return "未配置群链接";
        $url = $robot[0]["url"];
        $headers = ['Content-Type: application/json'];
        $data = [
            'msgtype'=>"image",
            "image"=>[
                "base64"=>base64_encode(file_get_contents($image)),
                "md5"=>md5(file_get_contents($image))
            ]
        ];
        $res = self::curl_post($url,$data,$headers);

        return $res;
	}
	/*
	* 机器人发送文本请求
	*/
	static public function robotText($text){
		$robot = Db::table('kt_base_robot')->select()->toArray();
		if(!$robot[0]) return "未配置群链接";
        $url = $robot[0]["url"];
        $headers = ['Content-Type: application/json'];
        $data = [
            'msgtype'=>"text",
            "text"=>[
                "content"=>$text
            ]
        ];
        $res = self::curl_post($url,$data,$headers);

        return $res;
    }

    //授权获取 员工 信息
    static public function getUserTicket($wid,$code){
    	$token = self::getSelfappAccessToken($wid);
    	$res = curlGet("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".$token."&code=".$code,array());
	    $resp_arr = json_decode($res, 1);
	    return $resp_arr;
    }

    static public function getUserDetail($wid,$data){
    	$token = self::getSelfappAccessToken($wid);
    	$res = curlPost("https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=".$token,
			json_encode($data)
		);
    	$resp_arr = json_decode($res, 1);

	    return $resp_arr;
    }

    static public function getUserInfos($wid,$userid){
    	$token = self::getSelfappAccessToken($wid);
    	$res = curlGet("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=".$token."&userid=".$userid,array());
    	$resp_arr = json_decode($res, 1);

	    return $resp_arr;
    }

    //获取朋友圈详情
    static public function getMomentTask($jobid,$wid=NULL){
    	$wid = Session::get("wid")?:$wid;
    	$token = self::getCustomerAccessToken($wid);
    	$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_task_result?access_token='.$token.'&jobid='.$jobid;
		$resArr = json_decode(curlGet($url),1);

	    return $resArr;
    }

    static public function getMoment($wid,$moment_id){
    	$wid = Session::get("wid")?:$wid;
    	$token = self::getCustomerAccessToken($wid);
    	$data["moment_id"] = $moment_id;
    	$data["limit"] = 1000;
    	$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_task?access_token='.$token;
		$resArr = json_decode(curlPost($url,json_encode($data)),1);

	    return $resArr;
    }

    static public function getMomentList($wid){
    	$wid = Session::get("wid")?:$wid;
    	$times = Db::table("kt_wework_moments_sync")->where(["wid"=>$wid])->find();
    	$token = self::getCustomerAccessToken($wid);
    	$data["start_time"] = strtotime("-30 day");
    	if($times)$data["start_time"] = $times["time"];
    	$data["end_time"] = time();
    	$data["filter_type"] = 1;
    	$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_list?access_token=".$token;
    	$res["moment_list"] = [];
    	while (1) {
			$info = json_decode(curlPost($url,json_encode($data)),1);
			if($info['errcode'] != 0){
				$res =  $info;
				break;
			}
			$res['moment_list'] = array_merge($res['moment_list'],$info['moment_list']);
			if($info['next_cursor'] == ''){
				break;
			}
			$data['cursor'] = $info['next_cursor'];
		}
		if(!$times)Db::table("kt_wework_moments_sync")->insertGetId(["wid"=>$wid,"time"=>time()]);
		if($times)Db::table("kt_wework_moments_sync")->where(["wid"=>$wid])->save(["wid"=>$wid,"time"=>time()]);
		
    	return $res;
    }

    //获取客户朋友圈发表后的可见客户列表
    static public function getMomentSendResult($moment_id,$userid,$wid=NULL){
    	$wid = Session::get("wid")?:$wid;
    	$token = self::getCustomerAccessToken($wid);
    	$data["moment_id"] = $moment_id;
    	$data["userid"] = $userid;
    	$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_send_result?access_token=".$token;
    	$res = curlPost($url,json_encode($data));
    	$resp_arr = json_decode($res, 1);

	    return $resp_arr;
    }

    //发布朋友圈
    static public function addMomentTask($staffs,$tags,$text,$attachments,$wid=NULL){
    	$wid = Session::get("wid")?:$wid;
    	$token = self::getCustomerAccessToken($wid);
    	$res = curlPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_moment_task?access_token=".$token,
			json_encode([
				"text"=>[
					"content"=>$text
				],
				"attachments"=>$attachments,
				"visible_range"=>[
					"sender_list"=>[
						"user_list"=>$staffs
					]
				],
				"external_contact_list"=>[
					"tag_list"=>$tags
				]
			])
		);
    	$resp_arr = json_decode($res, 1);

	    return $resp_arr;
    }

    static public function groupBehavior($wid,$staffs,$ktime,$dtime){
    	$wid = Session::get("wid")?:$wid;
    	$token = self::getCustomerAccessToken($wid);
        $body = curlPost(
	    	"https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic_group_by_day?access_token=".$token,
	    	json_encode([
	      		'owner_filter' => [
	      		        "userid_list"=>$staffs
	      		    ],
	            'day_begin_time' => $ktime,
	            'day_end_time' => $dtime,
	    	])
	  	);
	 	$resp_arr = json_decode($body, 1);
        return $resp_arr;
    }

    static public function groupUserBehavior($wid,$staffs,$ktime,$dtime){
    	$wid = Session::get("wid")?:$wid;
    	$token = self::getCustomerAccessToken($wid);
        $body = curlPost(
	    	"https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic?access_token=".$token,
	    	json_encode([
	      		'owner_filter' => [
	      		    "userid_list"=>[$staffs]
	      		    ],
	            'day_begin_time' => $ktime,
	            'day_end_time' => $dtime,
	            'order_by' => 4
	    	])
	  	);
	 	$resp_arr = json_decode($body, 1);
        return $resp_arr;
    }

    static public function curl_post($url,$data,$headers){
    	$curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode( $data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($curl); // 执行操作
        return $result;
    }
}